#!/usr/bin/ruby
# -*- ruby -*-
#
# http://www.reddit.com/r/dailyprogrammer/comments/106go0/9202012_challenge_100_easy_sleep_cycle_estimator/

require 'optparse'
require 'time'

class TimeRange
  attr_reader :start, :stop, :delta, :current

  def initialize(start, stop, delta)
    @start = start
    @stop  = stop
    @delta = delta

    @current = @start
  end

  def has_next?
    return (@current + @delta) < @stop
  end

  def step
    return (has_next? ? (@current += @delta) : nil)
  end
end

wakeup_time = nil
sleep_time  = nil

OptionParser.new do |o|
  o.on("-w", "--wakeup-time=WAKEUP", String) { |wakeup_time| }
  o.on("-s", "--sleep-time=SLEEP", String)   { |sleep_time| }
end.parse!

# Parse and set both wakeup and sleep times based on what's
# specified as input
#
# Prefer the sleep_time if it's set and set wakeup 8 hours later
#
# Make sure we're waking up the next day
if sleep_time
  sleep_time  = Time.parse(sleep_time)
  wakeup_time = sleep_time + 8 * 60 * 60
else
  sleep_time  = Time.now
  wakeup_time = wakeup_time ? Time.parse(wakeup_time) : (Time.parse("06:15 AM") + 24 * 60 * 60)
end

raise "Wakeup time must be in the future!" if wakeup_time && Time.now > wakeup_time

# Build our time range
range = TimeRange.new(sleep_time, wakeup_time, 90 * 60)

while range.has_next?
  puts range.step
end
